package com.lanou.utp.utils;

import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ExcelUtils {

    public static SXSSFSheet createSheet(SXSSFWorkbook workbook,String sheetName,String[] header){

        SXSSFSheet sheet = workbook.createSheet(sheetName);
        //设置行高为两个字符的高度
        sheet.setDefaultRowHeight((short)(2*256));
        //设置列宽
        sheet.setDefaultColumnWidth(17);
        SXSSFRow row = sheet.createRow(0);

        SXSSFCell cell = null;
        for (int i = 0; i < header.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(header[i]);
        }
        return sheet;
    }

    public static void excelOutput(HttpServletResponse response, String fileName, SXSSFWorkbook workbook){
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
